package com.pj.lib.aura.storage;

import java.util.HashMap;

import com.pj.lib.aura.storage.AuraDB.UserLocationsColumns;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;

public class AuraProvider extends ContentProvider {
	
	private static final String TAG = "AuraProvider";
	
	private static final int DATABASE_VERSION = 1;
	private static final String DATABASE_NAME = "aura.db";
    private static final String TABLE_NAME = "users_locations";
    
  
    private static final int LOCATIONS = 1;
    private static final int LOCATION_ID = 2;
    
    private static HashMap<String, String> sLocationsProjectionMap;
    
    private static final UriMatcher sUriMatcher;
	
	public class LocationDB extends SQLiteOpenHelper{

		
	    
	    private static final String TABLE_CREATE =
	                "CREATE TABLE " + TABLE_NAME + " (" +
	                UserLocationsColumns._ID + " INTEGER PRIMARY KEY," +
	                UserLocationsColumns.USER_ID + " TINYINT NOT NULL, " +
	                UserLocationsColumns.NICK_NAME + " VARCHAR(50) NOT NULL, " +
	                UserLocationsColumns.LONGITUDE + " NUMERIC(10,7) NOT NULL, " +
	                UserLocationsColumns.LATITUDE + " NUMERIC(10,7) NOT NULL, " + 
	                UserLocationsColumns.ACCURACY + " NUMERIC(3, 0) NOT NULL, " +
	                UserLocationsColumns.TIME + " DATETIME NOT NULL);";
	                
	                

		public LocationDB(Context context) {
			super(context, DATABASE_NAME, null, DATABASE_VERSION);
		}
	    
		@Override
		public void onCreate(SQLiteDatabase db) {
			db.execSQL(TABLE_CREATE);
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
                    + newVersion + ", which will destroy all old data");
            db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
            onCreate(db);
		}
		
		

	}
	
	private LocationDB mOpenHelper;

	@Override
	public boolean onCreate() {
		mOpenHelper = new LocationDB(getContext());
        return true;
	}
	
	@Override
	public Cursor query(Uri uri, String[] projection, String selection,
			String[] selectionArgs, String sortOrder) {
		SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
        qb.setTables(TABLE_NAME);

        switch (sUriMatcher.match(uri)) {
        case LOCATIONS:
            qb.setProjectionMap(sLocationsProjectionMap);
            break;

        case LOCATION_ID:
            qb.setProjectionMap(sLocationsProjectionMap);
            qb.appendWhere(UserLocationsColumns._ID + "=" + uri.getPathSegments().get(1));
            break;

        default:
            throw new IllegalArgumentException("Unknown URI " + uri);
        }

        // If no sort order is specified use the default
        String orderBy;
        if (TextUtils.isEmpty(sortOrder)) {
            orderBy = UserLocationsColumns.DEFAULT_SORT_ORDER;
        } else {
            orderBy = sortOrder;
        }

        // Get the database and run the query
        SQLiteDatabase db = mOpenHelper.getReadableDatabase();
        Cursor c = qb.query(db, projection, selection, selectionArgs, null, null, orderBy);

        // Tell the cursor what uri to watch, so it knows when its source data changes
        c.setNotificationUri(getContext().getContentResolver(), uri);
        return c;
	}
	
	@Override
	public int delete(Uri uri, String where, String[] whereArgs) {
		SQLiteDatabase db = mOpenHelper.getWritableDatabase();
        int count;
        switch (sUriMatcher.match(uri)) {
        case LOCATIONS:
            count = db.delete(TABLE_NAME, where, whereArgs);
            break;

        case LOCATION_ID:
            String noteId = uri.getPathSegments().get(1);
            count = db.delete(TABLE_NAME, UserLocationsColumns._ID + "=" + noteId
                    + (!TextUtils.isEmpty(where) ? " AND (" + where + ')' : ""), whereArgs);
            break;

        default:
            throw new IllegalArgumentException("Unknown URI " + uri);
        }

        getContext().getContentResolver().notifyChange(uri, null);
        return count;
	}

	@Override
	public String getType(Uri uri) {
		switch (sUriMatcher.match(uri)) {
        case LOCATIONS:
            return UserLocationsColumns.CONTENT_TYPE;
        case LOCATION_ID:
            return UserLocationsColumns.CONTENT_ITEM_TYPE;

        default:
            throw new IllegalArgumentException("Unknown URI " + uri);
        }
	}

	@Override
	public Uri insert(Uri uri, ContentValues initialValues) {
		// Validate the requested uri
        if (sUriMatcher.match(uri) != LOCATIONS) {
            throw new IllegalArgumentException("Unknown URI " + uri);
        }

        ContentValues values;
        if (initialValues != null) {
            values = new ContentValues(initialValues);
        } else {
            values = new ContentValues();
        }

        SQLiteDatabase db = mOpenHelper.getWritableDatabase();
        long rowId = db.insert(TABLE_NAME, null, values);
        if (rowId > 0) {
            Uri noteUri = ContentUris.withAppendedId(UserLocationsColumns.CONTENT_URI, rowId);
            getContext().getContentResolver().notifyChange(noteUri, null);
            return noteUri;
        }

        throw new SQLException("Failed to insert row into " + uri);
	}

	

	@Override
	public int update(Uri uri, ContentValues values, String where,
			String[] whereArgs) {
		SQLiteDatabase db = mOpenHelper.getWritableDatabase();
        int count;
        switch (sUriMatcher.match(uri)) {
        case LOCATIONS:
            count = db.update(TABLE_NAME, values, where, whereArgs);
            break;

        case LOCATION_ID:
            String noteId = uri.getPathSegments().get(1);
            count = db.update(TABLE_NAME, values, UserLocationsColumns._ID + "=" + noteId
                    + (!TextUtils.isEmpty(where) ? " AND (" + where + ')' : ""), whereArgs);
            break;

        default:
            throw new IllegalArgumentException("Unknown URI " + uri);
        }

        getContext().getContentResolver().notifyChange(uri, null);
        return count;
	}
	
	
	static {
        sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
        sUriMatcher.addURI(AuraDB.AUTHORITY, "userLocations", LOCATIONS);
        sUriMatcher.addURI(AuraDB.AUTHORITY, "userLocations/#", LOCATION_ID);

        sLocationsProjectionMap = new HashMap<String, String>();
        sLocationsProjectionMap.put(UserLocationsColumns._ID, UserLocationsColumns._ID);
        sLocationsProjectionMap.put(UserLocationsColumns.USER_ID, UserLocationsColumns.USER_ID);
        sLocationsProjectionMap.put(UserLocationsColumns.NICK_NAME, UserLocationsColumns.NICK_NAME);
        sLocationsProjectionMap.put(UserLocationsColumns.LONGITUDE, UserLocationsColumns.LONGITUDE);
        sLocationsProjectionMap.put(UserLocationsColumns.LATITUDE, UserLocationsColumns.LATITUDE);
        sLocationsProjectionMap.put(UserLocationsColumns.ACCURACY, UserLocationsColumns.ACCURACY);
        sLocationsProjectionMap.put(UserLocationsColumns.TIME, UserLocationsColumns.TIME);
        

    }
	
}

